package org.example.springsecuritydemo02.utils;

import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.gson.io.GsonSerializer;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

public class JwtUtil {

    public static final Long JWT_TTL = 60*60*1000L; // 1小时
    public static final String JWT_KEY = "abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234";

    public static String getUUID()
    {
        String token = UUID.randomUUID().toString().replace("-","");
        return token;
    }

    public static String createJWT(String subject,Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject,ttlMillis,getUUID());
        return builder.compact();
    }

    public static JwtBuilder getJwtBuilder(String subject,Long ttlMillis,String uuid)
    {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis == null)
        {
            ttlMillis = JwtUtil.JWT_TTL;
        }
        long expMills = nowMillis + ttlMillis;
        Date expDate = new Date(expMills);

        return Jwts.builder()
                .setId(uuid)
                .setSubject(subject)
                .setIssuer("xx")
                .setIssuedAt(now)
                .signWith(signatureAlgorithm,secretKey)
                .serializeToJsonWith(new GsonSerializer<>(new Gson()))
                .setExpiration(expDate);

    }

    public static SecretKey generalKey()
    {
        byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        // HmacSHA256
        SecretKey key = new SecretKeySpec(encodeKey,0,encodeKey.length,"HmacSHA256");
//        SecretKey key = new SecretKeySpec(encodeKey,0,encodeKey.length,"AES");
        return key;
    }


//    public static Claims parseJWT(String jwt) throws Exception
//    {
//        SecretKey secretKey = generalKey();
//        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
//    }
}
